如何在 VBA Excel 中使用 IF 和 OR ? (教程 2023) | 您所在的位置:网站首页 › vba for if嵌套 › 如何在 VBA Excel 中使用 IF 和 OR ? (教程 2023) |
您可以将OR运算符与VBA IF 语句结合使用来测试多个条件。当您使用它时,它允许您同时测试两个或多个条件,并在其中任何一个条件为 true 时返回 true 。但如果所有条件均为 false,则仅在结果中返回 false。 将 OR 与 IF 结合使用首先,以关键字“IF”开始 IF 语句。之后,指定您要测试的第一个条件。然后使用 OR 关键字指定第二个条件。最后,指定要测试的第二个条件。![]() 为了更好地理解,让我们看一个例子。 Sub myMacro() 'two conditions to test using OR If 1 = 1 Or 2 < 1 Then MsgBox "One of the conditions is true." Else MsgBox "None of the conditions are true." End If End Sub![]() 如果你看上面的例子,我们指定了两个条件,一个是 if (1 = 1),第二个是 (2 < 1),这里只有第一个条件为真,即使它执行了我们要执行的那行代码指定结果是否为真。 ![]() 现在让我们看看这两个条件是否都为假,让我在这里使用不同的代码。 Sub myMacro() 'two conditions to test using OR If 1 = 2 Or 2 < 1 Then MsgBox "One of the conditions is true." Else MsgBox "None of the conditions are true." End If End Sub![]() 在上面的代码中,两个条件都为 false,当您运行此代码时,如果结果为 false,它将执行我们指定的代码行。 ![]() 同样,您也可以同时测试两个以上的条件。让我们继续上面的示例并添加第三个条件。 Sub myMacro() 'three conditions to test using OR If 1 = 1 And 2 > 1 And 1 - 1 = 0 Then MsgBox "one of the conditions is true." Else MsgBox "none of the conditions are true." End If End Sub![]() 我们现在有三个条件要测试,我们在第二个条件之后使用 OR 来指定第三个条件。正如您在上面了解到的,当您使用 OR 时,其中一个条件必须为真才能在结果中变为真。当您运行此代码时,它会执行我们指定为 true 的代码行。 ![]() 如果所有条件都为 false,就像您在以下代码中所做的那样,它将返回 false。 Sub myMacro() 'three conditions to test using OR If 1 < 1 And 2 < 1 And 1 + 1 = 0 Then MsgBox "one of the conditions is true." Else MsgBox "none of the conditions are true." End If End Sub![]() |
CopyRight 2018-2019 实验室设备网 版权所有 |